﻿using CommunServer.Model;
using Helper.ConverttHelper;
using Helper.Log;
using Helper.TcpSocket;
using System;
using System.Collections.Generic;
using System.Net;

namespace CommunServer
{
    
    /// <summary>
    /// 消息日志委托
    /// </summary>
    /// <param name="message"></param>
    public delegate void ShowLogHandle(string message);
    public class CommunServer
    {  /// <summary>
       /// 记录日志
       /// </summary>
        public event ShowLogHandle LogEvent;

        /// <summary>
        /// tcp 服务
        /// </summary>
        private TcpService _server;
        /// <summary>
        /// 客户端列表
        /// key 通信
        /// val 设备Id
        /// </summary>
        private readonly Dictionary<EndPoint, int> _clientS = new Dictionary<EndPoint, int>();



        /// <summary>
        /// 构造方法
        /// </summary> 
        /// <param name="port"></param>
        public CommunServer(int port)
        {

            //在指定端口上建立监听线程
            _server = new TcpService(port);
            _server.Connected += server_Connected;
            _server.DisConnect += server_DisConnect;
            _server.Start();

        }
        /// <summary>
        /// 连接开始
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void server_Connected(IDataTransmit sender, NetEventArgs e)
        {
            LogEvent?.Invoke(DateTime.Now.ToLongTimeString() + " " + sender.RemoteEndPoint + " 连接成功");
            sender.ReceiveData += ReceiveData;

            if (!_clientS.ContainsKey(sender.RemoteEndPoint))
            {
                _clientS.Add(sender.RemoteEndPoint, 0);
            }
            //接收数据
            sender.Start();

        }
        /// <summary>
        /// 断开连接
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void server_DisConnect(IDataTransmit sender, NetEventArgs e)
        {

            if (_clientS.ContainsKey(sender.RemoteEndPoint))
            {
                _clientS.Remove(sender.RemoteEndPoint);
            }


            LogEvent?.Invoke(DateTime.Now.ToLongTimeString() + " " + sender.RemoteEndPoint + " 连接断开");
        }



        /// <summary>
        /// 接收消息 处理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void ReceiveData(IDataTransmit sender, NetEventArgs e)
        {
            try
            {
                byte[] data = (byte[])e.EventArg;
                LogEvent?.Invoke(DateTime.Now.ToLongTimeString() + " " + sender.RemoteEndPoint + " 接收数据\r\n" + TestUtil.GetHexOutput(data));
             //   byte[] bytes = StructToBytes(d);
                PakLoginReq s = (PakLoginReq)StructHelper.BytesToStuct(data, typeof(PakLoginReq));
                var s1 = s.ToString();
                sender.Send(data);
            }
            catch (Exception ex)
            {

                ILog log = LogFactory.GetLogger("CommunServer");
                log.Debug(ex);

            }

        }




        /// <summary>
        /// 停止监听
        /// </summary>
        public void Stop()
        {
            _server.Close();
            _server = null;
        }




    }

}
